package fr.xmlParser.pierop.com;

import java.io.File;
import java.util.Iterator;
import java.util.List;

import org.jdom.Element;
import org.jdom.input.SAXBuilder;

import fr.myExceptions.pierop.com.fileXmlException;
import fr.myExceptions.pierop.com.filterXmlException;



public class XmlParser implements IXmlParser {

	private static XmlParser singletonObject = null;
	
	private SAXBuilder			SAXInstance = null;
	private org.jdom.Document 	Document = null;
	private Element 			Root = null;
	
	private XmlParser()	{	this.SAXInstance = new SAXBuilder();	}
	
	public static XmlParser getInstance()
	{
		if (singletonObject == null) {	singletonObject = new XmlParser();	}
		return singletonObject;
	}
	
	public void setFile(String File) throws Exception {
		try	
		{
			this.Document = this.SAXInstance.build(new File(File));
			this.Root = this.Document.getRootElement();
	    }
		catch(Exception e)
		{
			throw new fileXmlException(IXmlParser.FileError);
		}
	}
	
	public List<Element> setFilter(String name) throws Exception {
		
		if (this.Document == null || this.Root == null)
			throw new filterXmlException();
		
		return	this.Root.getChildren(name);
	}
	
	public void affFilter(String name) throws Exception {
		
		if (this.Document == null || this.Root == null)
			throw new filterXmlException();
		
		List<Element> values = this.Root.getChildren(name);
		System.out.println(name + values);
		Iterator<Element> it = values.iterator();
		while (it.hasNext()) { 
			System.out.println("racine " + name + " : ");
			this.affRecur(it.next()); 
			}
	}
	
	private void affRecur(Element cur) {
		
		List<Element> values = cur.getChildren();
		Iterator<Element> it = values.iterator();
		while (it.hasNext()) {
			Element tmp = it.next();
			System.out.println("valeur " + tmp.getName() + " : " + tmp.getText());
			this.affRecur(tmp);
			}
		}
}
